import net.sf.ehcache.Element;
import java.net.URLDecoder;
class StatusController {
	
	
	def twitterCache
	def index = { 
		def messages = twitterCache.get(principalInfo.username)?.value
		if(!messages){
			messages = findStatusMessages()
			// Put a new Element if it is not found into the cache
			twitterCache.put new Element(principalInfo.username, messages)	
		}
		[ messages:findStatusMessages()]
	}
	
	private findStatusMessages(){
		def p = lookupPerson()
		
		def messages = Status.withCriteria{
			or{
				person {
					eq('username',p.username)
				}
				if(p.following) {
					inList ('person', p.following)
				} 		
			}
			maxResults 10
			order  'dateCreated' , 'desc'
		}
		
		return messages
	}
	
	def update = {
		def status = new Status(params)
		status.person = lookupPerson()
		status.save()
		
		//	to Remove the Element from the Cache after Updates are made to a User
		twitterCache.remove(principalInfo.username)
		
		def messages = findStatusMessages()
		
		render template:"message", var: "status", collection: messages
			
	}
	
	def follow = {		
		def p = Person.get(URLDecoder.decode(params.id))
		
		if(p){
			def current = lookupPerson()
			current.addToFollowing(p)
			current.save()
		}
		redirect action:"index"
	}
			
	private lookupPerson(){
		Person.findByUsername(principalInfo.username)
	}		
			
	
}